package com.scut.project.audio;

import javax.sound.sampled.*;
import java.io.File;
import java.io.IOException;

public class AudioRecorder {
    // 定义音频格式
    AudioFormat format = new AudioFormat(16000, 16, 1, true, true);
    TargetDataLine microphone;
    File outputFile = new File("recorded_audio.wav");

    public void startRecording() {
        try {
            // 获取麦克风数据行
            DataLine.Info info = new DataLine.Info(TargetDataLine.class, format);
            microphone = (TargetDataLine) AudioSystem.getLine(info);
            microphone.open(format);
            microphone.start();

            System.out.println("开始录音...");

            // 创建一个单独的线程将音频写入文件
            new Thread(() -> {
                try (AudioInputStream audioStream = new AudioInputStream(microphone)) {
                    AudioSystem.write(audioStream, AudioFileFormat.Type.WAVE, outputFile);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }).start();
        } catch (LineUnavailableException e) {
            e.printStackTrace();
        }
    }

    public void stopRecording() {
        microphone.stop();
        microphone.close();
        System.out.println("录音结束。文件已保存到：" + outputFile.getAbsolutePath());
    }

    public static void main(String[] args) {
        AudioRecorder recorder = new AudioRecorder();
        // 开始录音
        recorder.startRecording();

        // 停止录音的时间 (例如：10秒)
        try {
            Thread.sleep(10000); // 录音10秒
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        // 停止录音
        recorder.stopRecording();
    }
}
